/**
 * There are <a href="https://github.com/ketayao/keta-custom">keta-custom</a> code generation
 */
package fms.controller;

import com.ketayao.ketacustom.entity.main.User;
import com.ketayao.ketacustom.log.Log;
import com.ketayao.ketacustom.service.ModuleService;
import com.ketayao.ketacustom.service.UserService;
import com.ketayao.ketacustom.util.dwz.AjaxObject;
import com.ketayao.ketacustom.util.dwz.Page;
import com.ketayao.ketacustom.util.persistence.DynamicSpecifications;
import com.ketayao.ketacustom.util.persistence.SearchFilter;
import com.ketayao.ketacustom.util.persistence.SearchFilter.Operator;
import fms.core.DateUtil;
import fms.core.FLPXmlBuilder;
import fms.core.SysConstants;
import fms.entity.CptSend;
import fms.service.CptSendService;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("")
public class CptSendController {

    @Autowired
    private CptSendService cptSendService;

    @Autowired
    private JmsTemplate jmsTemplateQueueOut;

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    private static final String SHOWFLIGHTPLAN = "/common/showFlightPlan";
    private static final String SHOWWINDINFO = "/common/showWindInfo";
    private static final String SHOWWINDINFOS = "/common/showWindInfos";
    private static final String QFLIGHTPLANLIST = "/query/qFlightPlanList";
    private static final String QWINDINFOLIST = "/query/qWindInfoList";
    private static final String MFLIGHTPLANLIST = "/monitor/mFlightPlanList";
    private static final String MWINDINFOLIST = "/monitor/mWindInfoList";

    @RequestMapping(value = "/monitor/monitor", method = {RequestMethod.GET, RequestMethod.POST})
    public String monitor(ServletRequest request, Page page, Map<String, Object> map) {
        return "/monitor/monitor";
    }

    // 监控飞行计划（筛选）
    @RequestMapping(value = "/monitor/monitor/load", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map monitor(ServletRequest request, ServletResponse responese) throws ParseException, InterruptedException {
        Map<String, Object> map = new HashMap<>();

        Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        User user = userService.getByUsername(subject.getPrincipal().toString());
        String userOrg = user.getOrganization().getAirlines();

        //飞行计划
        List<SearchFilter> searchFilter = new ArrayList<SearchFilter>();
        // 管理员，可以查看所有用户数据（添加公司时，如果该公司没有二字码，不可以配置2个字符的字符串作为伪二字码）
        if (null != userOrg && userOrg.length() == 2) {
            searchFilter.add(new SearchFilter("airlines", Operator.EQ, userOrg));
        }
        searchFilter.add(new SearchFilter("sendType", Operator.EQ, "2"));
        searchFilter.add(new SearchFilter("depDate", Operator.GTE, DateUtil.getUTCTime(SysConstants.FORMAT_DATETIME_FULL,-350-2)));
        searchFilter.add(new SearchFilter("depDate", Operator.LTE, DateUtil.getUTCTime(SysConstants.FORMAT_DATETIME_FULL,-350+8)));
        System.out.println(DateUtil.getUTCTime(SysConstants.FORMAT_DATETIME_FULL,-216-2));	
        Page page = new Page();
        page.setNumPerPage(1000);
        page.setOrderField("depDate");
        page.setOrderDirection(Page.ORDER_DIRECTION_DESC);
        Specification<CptSend> specification = DynamicSpecifications.bySearchFilter(request, CptSend.class, searchFilter);
        List<CptSend> flightPlans = cptSendService.findByExample(specification, page);

        //风温信息
        searchFilter = new ArrayList<SearchFilter>();
        // 管理员，可以查看所有用户数据（添加公司时，如果该公司没有二字码，不可以配置2个字符的字符串作为伪二字码）
        if (null != userOrg && userOrg.length() == 2) {
            searchFilter.add(new SearchFilter("airlines", Operator.EQ, userOrg));
        }
        searchFilter.add(new SearchFilter("sendType", Operator.EQ, "1"));
        searchFilter.add(new SearchFilter("sendDate", Operator.GTE, DateUtil.getUTCTime(SysConstants.FORMAT_DATETIME_FULL,-144-2)));
        searchFilter.add(new SearchFilter("sendDate", Operator.LTE, DateUtil.getUTCTime(SysConstants.FORMAT_DATETIME_FULL,-144+8)));
        specification = DynamicSpecifications.bySearchFilter(request, CptSend.class, searchFilter);
        page.setOrderField("sendDate");
        page.setOrderDirection(Page.ORDER_DIRECTION_DESC);
        List<CptSend> windInfos = cptSendService.findByExample(specification, page);
        for (CptSend flightPlan : flightPlans) {
            for (CptSend wind : windInfos) {
                if (wind.getFlightId().equals(flightPlan.getFlightId())
                        && wind.getAircraftId().equals(flightPlan.getAircraftId())) {
                    if (flightPlan.getWindInfos() == null) {
                        flightPlan.setWindInfos(new ArrayList<CptSend>());
                    }
                    boolean exist= false;
                    for(CptSend filghtWind : flightPlan.getWindInfos()){
                        if(filghtWind.getFlightLevels().equals(wind.getFlightLevels())){
                            exist = true;
                            break;
                        }
                    }
                    if(!exist){
                        flightPlan.getWindInfos().add(wind);
                    }
                }
            }
        }
        map.put("flightPlans", flightPlans);

        return map;
    }

    @InitBinder
    public void dataBinder(WebDataBinder dataBinder) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(df, true));
    }

    // 点击左侧"查询飞行计划"菜单和"该tab页时"时，返回无数据的页面==>可在模块管理中配置
    @RequestMapping(value = "/query/firstlist", method = {RequestMethod.GET})
    public String firstlist() {
        return QFLIGHTPLANLIST;
    }

    // 点击左侧"查询风温数据"菜单和"该tab页时"时，返回无数据的页面==>可在模块管理中配置
    @RequestMapping(value = "/query/firstlistwid", method = {RequestMethod.GET})
    public String firstlistwid() {
        return QWINDINFOLIST;
    }


    // 查询飞行计划（搜索按钮）
    @Log(message = "查询飞行计划")
    @RequestMapping(value = "/query/flightPlan/load", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map qFlightPlanList(ServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        String pageNum = request.getParameter("pageNum");
        Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        User user = userService.getByUsername(subject.getPrincipal().toString());
        String userOrg = user.getOrganization().getAirlines();
        List<SearchFilter> searchFilter = new ArrayList<SearchFilter>();
        // 管理员，可以查看所有用户数据（添加公司时，如果该公司没有二字码，不可以配置2个字符的字符串作为伪二字码）
        if (null != userOrg && userOrg.length() == 2) {
            searchFilter.add(new SearchFilter("airlines", Operator.EQ, userOrg));
        }
        searchFilter.add(new SearchFilter("sendType", Operator.EQ, "2"));
        Specification<CptSend> specification = DynamicSpecifications
                .bySearchFilter(request, CptSend.class, searchFilter);
        Page page = new Page();
        page.setNumPerPage(100);
        if(pageNum!=null && !pageNum.equals("")){
            page.setPageNum(Integer.parseInt(pageNum));
        }
        page.setOrderField("planDate");
        page.setOrderDirection(Page.ORDER_DIRECTION_DESC);
        List<CptSend> cptSends = cptSendService.findByExample(specification, page);

        map.put("page", page);
        map.put("cptSends", cptSends);

        return map;
    }

    // 查询风温回复报文（搜索按钮）
    @RequestMapping(value = "/query/windInfo/load", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Map qWindInfoList(ServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        String pageNum = request.getParameter("pageNum");

        Subject subject = org.apache.shiro.SecurityUtils.getSubject();
        User user = userService.getByUsername(subject.getPrincipal().toString());
        String userOrg = user.getOrganization().getAirlines();

        List<SearchFilter> searchFilter = new ArrayList<SearchFilter>();
        // 管理员，可以查看所有用户数据（添加公司时，如果该公司没有二字码，不可以配置2个字符的字符串作为伪二字码）
        if (null != userOrg && userOrg.length() == 2) {
            searchFilter.add(new SearchFilter("airlines", Operator.EQ, userOrg));
        }
        searchFilter.add(new SearchFilter("sendType", Operator.EQ, "1"));
        Specification<CptSend> specification = DynamicSpecifications
                .bySearchFilter(request, CptSend.class, searchFilter);

        Page page = new Page();
        page.setNumPerPage(100);
        if(pageNum!=null && !pageNum.equals("")){
            page.setPageNum(Integer.parseInt(pageNum));
        }
        page.setOrderField("sendDate");
        page.setOrderDirection(Page.ORDER_DIRECTION_DESC);
        List<CptSend> cptSends = cptSendService.findByExample(specification, page);

        map.put("page", page);
        map.put("cptSends", cptSends);

        return map;
    }

    // 航班飞行计划发送功能
    @RequestMapping(value = "/common/sendFlightPlan", method = RequestMethod.POST)
    @ResponseBody
    public String sendFlightPlan(Long id, String sendContent, String replySMI, String flightId, String aircraftId) {
        CptSend cptSend = cptSendService.get(id);
        cptSend.setSendContent(sendContent);

        final String freeAllOutUPMsg = FLPXmlBuilder.build(flightId, aircraftId, sendContent, replySMI);

        cptSend.setSendStatus("1");
        cptSend.setSendDate(DateUtil.getUTCTime());
        cptSendService.saveOrUpdate(cptSend);
        jmsTemplateQueueOut.send(jmsTemplateQueueOut
                .getDefaultDestinationName(), new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                TextMessage message = session.createTextMessage(freeAllOutUPMsg);
                Logger logger = LoggerFactory.getLogger(CptSendController.class);
                logger.info("发送飞行计划acars报文内容是:" + freeAllOutUPMsg);
                return message;
            }
        });
//        LogUitls.putArgs(LogMessageObject.newWrite().setObjects(
//                new Object[]{cptSend.getFlightId(), cptSend.getAircraftId()}));

        return AjaxObject.newOk("发送飞行计划成功！").toString();
    }

    // 指定飞行计划的查看功能
    @RequestMapping(value = "/common/showFlightPlan/{id}", method = RequestMethod.GET)
    public String showFlightPlan(@PathVariable Long id, Map<String, Object> map) {
        CptSend cptSend = cptSendService.get(id);
        map.put("cptSend", cptSend);
        if (cptSend.getSendContent() != null) {
            map.put("msgbody", cptSend.getSendContent());
        } else {
            String upmsg = cptSendService.buildMsg(cptSend);
            map.put("msgbody", upmsg);
        }
        return SHOWFLIGHTPLAN;

    }

    // 指定风温回复信息的查看功能
    @RequestMapping(value = "/common/showWindInfo/{id}", method = RequestMethod.GET)
    public String showWindInfo(@PathVariable Long id, Map<String, Object> map) {
        CptSend cptSend = cptSendService.get(id);
        map.put("cptSend", cptSend);
        return SHOWWINDINFO;
    }

    /**
     *  根据指定风温回复信息的查看功能
     * */
    @RequestMapping(value = "/common/showWindInfos", method = RequestMethod.GET)
    public String showWindInfos(ServletRequest request,Map<String, Object> map) {
        String ids = request.getParameter("ids");
        //风温信息
        List<SearchFilter> searchFilter = new ArrayList<SearchFilter>();
        searchFilter.add(new SearchFilter("sendType", Operator.EQ, "1"));
        searchFilter.add(new SearchFilter("id", Operator.IN,ids.split(",")));
        Specification specification = DynamicSpecifications.bySearchFilter(request, CptSend.class, searchFilter);
        Page page = new Page();
        page.setNumPerPage(100);
        page.setOrderField("sendDate");
        page.setOrderDirection(Page.ORDER_DIRECTION_DESC);
        List<CptSend> cptSends = cptSendService.findByExample(specification,page);

        map.put("cptSends", cptSends);

        return SHOWWINDINFOS;
    }

    // 风温没有手动发送需求....
//	@Log(message = "发送id={0}风温数据信息。")
//	@RequestMapping(value = "/updatewid", method = RequestMethod.POST)
//	@ResponseBody
//	public String updatewid(Long id, String widContent) {
//
//		CptSend cptSend = cptSendService.get(id);
//		final String body = widContent;
//		cptSend.setSendContent(widContent);
//		cptSend.setSendStatus("1");
//		cptSend.setSendDate(DateUtil.getUTCTime() );
//		cptSendService.saveOrUpdate(cptSend);
//		jmsTemplateQueueOut.send(jmsTemplateQueueOut
//				.getDefaultDestinationName(), new MessageCreator() {
//			@Override
//			public Message createMessage(Session session) throws JMSException {
//				TextMessage message = session.createTextMessage(body);
//				return message;
//			}
//		});
//		LogUitls.putArgs(LogMessageObject.newWrite().setObjects(
//				new Object[] { cptSend.getId() }));
//		return AjaxObject.newOk("发送风温数据成功！").toString();
//	}

    // 风温和监控都是查询，暂无删除需求
//	@Log(message = "删除了id={0}任务。")
//	@RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
//	@ResponseBody
//	public String delete(@PathVariable Long id) {
//		cptSendService.delete(id);
//
//		LogUitls.putArgs(LogMessageObject.newWrite().setObjects(
//				new Object[] { id }));
//		return AjaxObject.newOk("任务删除成功！").setCallbackType("").toString();
//	}
//
//	@Log(message = "批量删除了id={0}任务。")
//	@RequestMapping(value = "/delete", method = RequestMethod.POST)
//	@ResponseBody
//	public String deleteMany(Long[] ids) {
//		for (int i = 0; i < ids.length; i++) {
//			CptSend task = cptSendService.get(ids[i]);
//			cptSendService.delete(task.getId());
//		}
//
//		LogUitls.putArgs(LogMessageObject.newWrite().setObjects(
//				new Object[] { Arrays.toString(ids) }));
//		return AjaxObject.newOk("任务删除成功！").setCallbackType("").toString();
//	}

    // 搭建框架时，用于测试
//	@RequestMapping(value = "/listindex", method = { RequestMethod.GET, RequestMethod.POST })
//	public String listindex(ServletRequest request, Page page,
//			Map<String, Object> map) {
//		Subject subject =org.apache.shiro.SecurityUtils.getSubject();
//		ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
//		User user = userService.getByUsername(subject.getPrincipal().toString());
//		
//System.out.println(shiroUser.getUser());	
//		Module menuModule = getMenuModule(SecurityUtils.getSubject());
// 
//		List<SearchFilter> searchFilter = new ArrayList<SearchFilter>();
//		searchFilter.add(new SearchFilter("sendType", Operator.EQ, "2"));
//		Specification<CptSend> specification = DynamicSpecifications
//				.bySearchFilter(request, CptSend.class, searchFilter);
//		page.setOrderField("planDate");
//		page.setOrderDirection(Page.ORDER_DIRECTION_ASC);
//		List<CptSend> cptSends = cptSendService.findByExample(specification, page);
//
//		map.put("page", page);
//		map.put("cptSends", cptSends);
//
//		return LISTINDEX;
//	}

    // 从IndexController中拷贝过来的代码，貌似没用
//	private Module getMenuModule(Subject subject) {
//		Module rootModule = moduleService.getTree();
//		check(rootModule, subject);
//		return rootModule;
//	}
//	
//		private void check(Module module, Subject subject) {
//			List<Module> list1 = new ArrayList<Module>();
//			for (Module m1 : module.getChildren()) {
//				// 只加入拥有show权限的Module
//				if (subject.isPermitted(m1.getSn() + ":" + Permission.PERMISSION_SHOW)) {
//					check(m1, subject);
//					list1.add(m1);
//				}
//			}
//			module.setChildren(list1);
//		}

    // 监控飞行计划（筛选）
//	@RequestMapping(value = "/monitor/mFlightPlanList", method = { RequestMethod.GET, RequestMethod.POST })
//	public String mFlightPlanList(ServletRequest request, Page page, Map<String, Object> map) {
//		Subject subject =org.apache.shiro.SecurityUtils.getSubject();
//		ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
//		User user = userService.getByUsername(subject.getPrincipal().toString());
//		String userOrg = user.getOrganization().getAirlines();
//
//		List<SearchFilter> searchFilter = new ArrayList<SearchFilter>();
//		// 管理员，可以查看所有用户数据（添加公司时，如果该公司没有二字码，不可以配置2个字符的字符串作为伪二字码）
//		if (null != userOrg && userOrg.length() == 2) {
//			searchFilter.add(new SearchFilter("airlines", Operator.EQ, userOrg));
//		}
//		searchFilter.add(new SearchFilter("sendType", Operator.EQ, "2"));
//		searchFilter.add(new SearchFilter("planDate", Operator.GTE,  DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE)));
//		searchFilter.add(new SearchFilter("planDate", Operator.LTE,	DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE)));
//
//		Specification<CptSend> specification = DynamicSpecifications
//				.bySearchFilter(request, CptSend.class, searchFilter);
//		page.setOrderField("planDate");
//		page.setOrderDirection(Page.ORDER_DIRECTION_DESC);
//		List<CptSend> cptSends = cptSendService.findByExample(specification,page);
//
//		map.put("page", page);
//		map.put("cptSends", cptSends);
//
//		return MFLIGHTPLANLIST;
//	}
//
    // 监控风温回复报文（筛选）
//	@RequestMapping(value = "/monitor/mWindInfoList", method = { RequestMethod.GET, RequestMethod.POST })
//	public String mWindInfoList(ServletRequest request, Page page, Map<String, Object> map) {
//		Subject subject =org.apache.shiro.SecurityUtils.getSubject();
//		ShiroUser shiroUser = (ShiroUser)subject.getPrincipal();
//		User user = userService.getByUsername(subject.getPrincipal().toString());
//		String userOrg = user.getOrganization().getAirlines();
//
//		List<SearchFilter> searchFilter = new ArrayList<SearchFilter>();
//		// 管理员，可以查看所有用户数据（添加公司时，如果该公司没有二字码，不可以配置2个字符的字符串作为伪二字码）
//		if (null != userOrg && userOrg.length() == 2) {
//			searchFilter.add(new SearchFilter("airlines", Operator.EQ, userOrg));
//		}
//		searchFilter.add(new SearchFilter("sendType", Operator.EQ, "1"));
//		searchFilter.add(new SearchFilter("sendDate", Operator.GTE,  DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE)));
//		searchFilter.add(new SearchFilter("sendDate", Operator.LTE,	DateUtil.getCurUTCtime(SysConstants.FORMAT_DATE)));
//		Specification<CptSend> specification = DynamicSpecifications
//				.bySearchFilter(request, CptSend.class, searchFilter);
//		page.setOrderField("sendDate");
//		page.setOrderDirection(Page.ORDER_DIRECTION_DESC);
//		List<CptSend> cptSends = cptSendService.findByExample(specification,page);
//
//		map.put("page", page);
//		map.put("cptSends", cptSends);
//
//		return MWINDINFOLIST;
//	}
}
